package disk;

import java.util.ArrayList;
import java.util.HashMap;

/**
 * 已带开文件列表
 * 
 * @author vincent
 * 
 */
public class OpenFileTable {
	/**
	 * 记录已打开文件的哈希表
	 */
	private HashMap<String, OpenFileTableItem> openFileHashMap = new HashMap<String, OpenFileTableItem>();
	/**
	 * 已打开文件列表
	 */
	private static OpenFileTable instance = null;

	/**
	 * 构造函数
	 */
	private OpenFileTable() {

	}

	/**
	 * 获取已打开文件列表实例
	 * 
	 * @return
	 */
	public static OpenFileTable getInstance() {
		if (OpenFileTable.instance == null) {
			OpenFileTable.instance = new OpenFileTable();
		}
		return OpenFileTable.instance;
	}

	/**
	 * 添加正在读取的文件
	 * 
	 * @param currentDirectory
	 * @param directoryEntry
	 */
	public boolean addtReadingFile(Directory currentDirectory,
			DirectoryEntry directoryEntry) {
		return addItem(currentDirectory, directoryEntry, 0);
	}

	/**
	 * 添加正在写入的文件
	 * 
	 * @param currentDirectory
	 * @param directoryEntry
	 */
	public boolean addtWritingFile(Directory currentDirectory,
			DirectoryEntry directoryEntry) {
		return addItem(currentDirectory, directoryEntry, 1);
	}

	/**
	 * 添加已打开文件
	 * 
	 * @param currentDirectory
	 * @param directoryEntry
	 */
	public boolean addItem(Directory currentDirectory,
			DirectoryEntry directoryEntry, int operationType) {
		// 判断文件是否已经打开
		if (isOpen(currentDirectory.getAbsolutePath(directoryEntry.getCompleteName()))) {
			return false;
		}
		OpenFileTableItem item = new OpenFileTableItem();
		item.setOperationType(operationType);
		String filePath = currentDirectory.getAbsolutePath(directoryEntry.getCompleteName());
		this.openFileHashMap.put(filePath, item);
		return true;
	}

	/**
	 * 移除记录
	 * 
	 * @param filePath
	 * @return
	 */
	public void removeItem(String filePath) {
		this.openFileHashMap.remove(filePath);
	}

	/**
	 * 判断文件是否已经打开
	 * 
	 * @param filePath
	 * @return
	 */
	public boolean isOpen(String filePath) {
		if (openFileHashMap.containsKey(filePath)) {
			return true;
		}
		return false;
	}

	/**
	 * 判断文件是否正在读取
	 * 
	 * @param filePath
	 * @return
	 */
	public boolean isReading(String filePath) {
		OpenFileTableItem item = openFileHashMap.get(filePath);
		if (item != null && item.getOperationType() == 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断文件是否正在写入
	 * 
	 * @param filePath
	 * @return
	 */
	public boolean isWriting(String filePath) {
		OpenFileTableItem item = openFileHashMap.get(filePath);
		if (item != null && item.getOperationType() == 1) {
			return true;
		}
		return false;
	}

}
